import { memo, useEffect, useRef, useState } from 'react'
import { ContentStyle } from './style'

const Content = memo(() => {
	const boxRef = useRef<HTMLDivElement>(null)

	const flog = useRef(false)

	const initWidth = useRef(0) // 初识宽度
	const start = useRef(0) // 起始位置

	const [width, setWidth] = useState<number>()

	const mousedown = (event: MouseEvent) => {
		start.current = event.pageX
		window.addEventListener('mousemove', mousemove)
		window.addEventListener('mouseup', mouseup)
	}

	const mouseup = () => {
		flog.current = false
		initWidth.current = boxRef.current?.clientWidth ?? 0
		window.removeEventListener('mousemove', mousemove)
		window.removeEventListener('mouseup', mouseup)
		window.removeEventListener('mousedown', mousedown)
	}

	const mousemove = (event: MouseEvent) => {
		if (flog.current) {
			const bar = start.current - event.pageX
			const foo = initWidth.current - bar
			setWidth(foo)
		}
	}

	useEffect(() => {
		initWidth.current = boxRef.current?.clientWidth ?? 0
	}, [])

	return (
		<ContentStyle ref={boxRef} style={{ width: width + 'px' }}>
			<div
				className="handle"
				onMouseDown={() => {
					flog.current = true
					window.addEventListener('mousedown', mousedown)
				}}
			></div>
		</ContentStyle>
	)
})

export default Content
